package com.heba.fragment.home;

import android.content.res.Resources;
import android.os.Bundle;

import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.android.material.tabs.TabLayout;
import com.heba.Cfg;
import com.heba.adapter.FmPagerAdapter;
import com.heba.bean.article.ItemArticleColumnObject;
import com.heba.config.CommonConfig;
import com.heba.event.MessageEvent;
import com.heba.fragment.BaseFragment;
import com.heba.greenmulu.R;
import com.heba.greenmulu.ScanActivity;
import com.heba.greenmulu.scan.ItemProductCategoryActivity;
import com.heba.helper.HttpClientHelper;
import com.heba.helper.JSONHttpHelper;
import com.heba.utils.IndicatorLineUtil;
import com.heba.view.ClearEditTextView;
import com.loopj.android.http.RequestParams;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * HomeFragment
 * Created by jason on 2019/2/13.
 */

public class HomeFragment extends BaseFragment {

    private ImageView img_view;
    private TabLayout tabLayout;
    private ViewPager viewPager;
    private FmPagerAdapter pagerAdapter;
    private ArrayList<Fragment> fragments = new ArrayList<>();
    private ConstraintLayout bottomLine1;
    private int selectIndex = 1;

    private List<ItemArticleColumnObject> itemArticleColumnObjects = new ArrayList<>();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_home, null);
        initView(view);
        getColumnData();
        return view;
    }

    private void initView(View view) {
        img_view = view.findViewById(R.id.img_logo);
//        img_logo.setForceDarkAllowed(false);
        tabLayout = view.findViewById(R.id.tablayout);
        viewPager = view.findViewById(R.id.viewpager);
        bottomLine1 = view.findViewById(R.id.bottom_line_1);
        //设置logo显示
        img_view.setImageResource(R.drawable.icon_logo);
        if (Cfg.Language == 1) {
            img_view.setImageResource(R.drawable.icon_logo);
        } else if (Cfg.Language == 2) {
            img_view.setImageResource(R.drawable.icon_logo_ch);
        }

    }

    /**
     * 填充栏目数据
     */
    private void setTabContentData() {
        /**
         * 添加tab
         */
        for (int i = 0; i < itemArticleColumnObjects.size(); i++) {
            fragments.add(ContentFragment.newInstance(itemArticleColumnObjects.get(i)));
            tabLayout.addTab(tabLayout.newTab());
        }

        /**
         * 关联viewpager,设置adapter
         */
        tabLayout.setupWithViewPager(viewPager, false);
        pagerAdapter = new FmPagerAdapter(fragments, getChildFragmentManager());
        viewPager.setAdapter(pagerAdapter);

        /**
         * 设置tab文字,必须在关联viewpager之后设置，否则文字不显示
         */
        for (int i = 0; i < itemArticleColumnObjects.size(); i++) {
            tabLayout.getTabAt(i).setText(itemArticleColumnObjects.get(i).getColumnName());
        }
        TextView title = (TextView) (((LinearLayout) ((LinearLayout) tabLayout.getChildAt(0)).getChildAt(0)).getChildAt(1));
        title.setTextAppearance(R.style.TabLayoutSelectedTextStyle1);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int position = tabLayout.getSelectedTabPosition();
                Resources resources = getResources();
                DisplayMetrics dm = resources.getDisplayMetrics();
                TextView title = (TextView) (((LinearLayout) ((LinearLayout) tabLayout.getChildAt(0)).getChildAt(tab.getPosition())).getChildAt(1));
                title.setTextAppearance(R.style.TabLayoutSelectedTextStyle1);
                int width3 = dm.widthPixels;
                TranslateAnimation translateAnimation1 = new TranslateAnimation((selectIndex)*(width3/itemArticleColumnObjects.size()),(position)*(width3/itemArticleColumnObjects.size()),0,0);
                translateAnimation1.setDuration(300);
                translateAnimation1.setFillEnabled(true);//使其可以填充效果从而不回到原地
                translateAnimation1.setFillAfter(true);//不回到起始位置
                bottomLine1.startAnimation(translateAnimation1);


                translateAnimation1.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        selectIndex = tabLayout.getSelectedTabPosition();

                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                TextView title = (TextView) (((LinearLayout) ((LinearLayout) tabLayout.getChildAt(0)).getChildAt(tab.getPosition())).getChildAt(1));
                title.setTextAppearance(R.style.TabLayoutNormalTextStyle1);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        /**
         * 设置指示线长度间隔(单位dp)
         */
        tabLayout.post(new Runnable() {
            @Override
            public void run() {
                IndicatorLineUtil.setIndicator(tabLayout, 0, 0);
            }
        });
    }

    /**
     * 获取文章栏目数据
     */
    private void getColumnData() {
        progressDialog.show();
        HttpClientHelper client = new HttpClientHelper();
        client.setUseLogin(true);
        RequestParams params = new RequestParams();
        params.put("Leng", Cfg.Leng);
        client.get(Cfg.BaseUrl + "/Article/ColumnList", params,
                new JSONHttpHelper.JSONHttpResponseHandler(getActivity()) {

                    @Override
                    public void Success() {
                        // TODO Auto-generated method stub
                        super.Success();
                        progressDialog.dismiss();
                        try {
                            JSONArray array = new JSONObject(response.trim()).getJSONArray("Result");
                            if (array.length() > 0) {
                                /**
                                 * 加载数据
                                 */
                                updateColumnData(array);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    public void Failure() {
                        super.Failure();
                        progressDialog.dismiss();
                    }

                });
    }

    /**
     * updateColumnData
     *
     * @param data
     */
    private void updateColumnData(JSONArray data) {

        /**
         * 添加all
         */
        ItemArticleColumnObject columnObject1 = new ItemArticleColumnObject();
        columnObject1.setColumnID("");
        columnObject1.setColumnName(getActivity().getResources().getString(R.string.all));
        itemArticleColumnObjects.add(columnObject1);

        for (int i = 0; i < data.length(); i++) {
            try {
                JSONObject object = data.getJSONObject(i);
                ItemArticleColumnObject columnObject = new ItemArticleColumnObject();
                columnObject.setColumnID(object.getString("ColumnID"));
                columnObject.setColumnName(object.getString("ColumnName"));
                itemArticleColumnObjects.add(columnObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        /**
         * 添加收藏的文章欄目
         */
        ItemArticleColumnObject columnObject2 = new ItemArticleColumnObject();
        columnObject2.setColumnID("");
        columnObject2.setColumnName(getActivity().getResources().getString(R.string.favorite));
        itemArticleColumnObjects.add(columnObject2);

        /**
         * 填充数据
         */
        setTabContentData();
    }

    @Override
    public void onStart() {
        super.onStart();
        if (!EventBus.getDefault().isRegistered(this))
            EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        /**
         * 接收事件
         */
        if (event.getEvent().equals(CommonConfig.HOME_REFRESH)) {
            if (null != tabLayout && tabLayout.getTabCount() > 0) {
                tabLayout.getTabAt(0).select();

                EventBus.getDefault().post(new MessageEvent(CommonConfig.SCROLL_TO_TOP));
            }
        }
    }
}
